package com.mtjx.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
//import com.mtjx.entitys.LoginUser;
import com.mtjx.entitys.entitys.LoginUser;
import com.mtjx.service.impl.UserDetailsServiceImpl;
import com.mtjx.utils.JwtUtil;
import com.mtjx.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 33117
 * @version 1.0
 * @data 2025/8/29 11:07
 * 过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("Authorization");
        if (token == null) {
            filterChain.doFilter(request, response);
            return;
        }

        // 解析token
        Claims claims = null;
        try {
             claims = JwtUtil.parseJWT("陌", token);
            if (claims == null) {
                return;
            }
        } catch (Exception e) {
            throw new RuntimeException("Token非法");
        }

        String username = (String) claims.get("username");
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        // 获取权限信息，添加到登录认证中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}
